package com.youbug.mall.product_pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youbug.common.vo.QueryVo;
import com.youbug.mall.product_pms.entity.PmsBrand;
import com.youbug.mall.product_pms.entity.PmsCategoryBrandRelation;
import com.youbug.mall.product_pms.mapper.PmsBrandMapper;
import com.youbug.mall.product_pms.service.IPmsBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youbug.mall.product_pms.service.IPmsCategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 品牌 服务实现类
 * </p>
 *
 * @author youbug
 * @since 2023-07-04
 */
@Service
public class PmsBrandServiceImpl extends ServiceImpl<PmsBrandMapper, PmsBrand> implements IPmsBrandService {

    @Autowired
    private IPmsCategoryBrandRelationService categoryBrandRelationService;

    @Override
    public IPage<PmsBrand> getPmsBrands(QueryVo<PmsBrand> queryVo) {

        Page<PmsBrand> page = new Page<>();

        page.setCurrent(queryVo.getCurrentPage());

        page.setSize(queryVo.getPageSize());

        QueryWrapper<PmsBrand> wrapper = new QueryWrapper<>();

        PmsBrand brand = queryVo.getPayload();

        if(!ObjectUtils.isEmpty(brand) && StringUtils.hasText(brand.getName())){
            wrapper.like("name", brand.getName()+"%");
        }

        if(!ObjectUtils.isEmpty(brand.getShowStatus())){
            wrapper.eq("show_status", brand.getShowStatus());
        }

        Page<PmsBrand> result = this.page(page, wrapper);

        return result;
    }

    @Override
    public Boolean changeShowStatus(Long brandId, Integer status) {
        PmsBrand pmsBrand = new PmsBrand();
        pmsBrand.setBrandId(brandId);
        pmsBrand.setShowStatus(status);

        boolean update = this.updateById(pmsBrand);

        return update;
    }

    @Override
    public List<PmsBrand> getBrandsByCatId(Long catId) {

        List<PmsCategoryBrandRelation> relations = categoryBrandRelationService
                .list(new QueryWrapper<PmsCategoryBrandRelation>().eq("catalog_id", catId));

        List<Long> brandIds = relations.stream().map(PmsCategoryBrandRelation::getBrandId).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(brandIds)){
            return null;
        }
        return this.listByIds(brandIds);
    }
}
